// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { checkId, checkData } = event
  
  try {
    // 生成需要整改的项目描述
    const failedItems = checkData.items.filter(item => item.score < item.maxScore * 0.6)
    let description = `本次检查总分${checkData.totalScore}分，低于及格线，需要整改以下项目：`
    let requirements = ''
    let images = []
    
    failedItems.forEach((item, index) => {
      description += `\n${index + 1}. ${item.name}：${item.score}/${item.maxScore}分`
      requirements += `${index + 1}. ${item.name}：${item.comment || '需改进'}\n`
      
      // 收集问题图片
      if (item.images && item.images.length > 0) {
        images = images.concat(item.images)
      }
    })
    
    // 限制图片数量
    if (images.length > 5) {
      images = images.slice(0, 5)
    }
    
    // 设置截止日期（3天后）
    const deadline = new Date()
    deadline.setDate(deadline.getDate() + 3)
    
    // 创建整改任务
    const taskData = {
      dormId: checkData.dormId,
      building: checkData.building,
      roomNo: checkData.roomNo,
      roomInfo: `${checkData.building}栋${checkData.roomNo}寝室`,
      checkId: checkId,
      title: "需要整改寝室环境",
      description: description,
      requirements: requirements,
      images: images,
      creatorId: wxContext.OPENID,
      checkerName: checkData.checkerName,
      createTime: new Date(),
      deadline: deadline,
      status: "待整改",
      notifyStatus: ["已通知"]
    }
    
    const result = await db.collection('tasks').add({
      data: taskData
    })
    
    return {
      success: true,
      taskId: result._id
    }
  } catch (error) {
    console.error('创建整改任务失败', error)
    return {
      success: false,
      error: error
    }
  }
} 